using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;

namespace HeroldIT.Dnn.Modules.News.Views
{
    public class NewsListSettings : SettingsBase, INewsListSettingsProvider
    {
        #region control fields

        // TODO: Add control fields here.
        protected ListControl lstDetailTabId;
        protected ICheckBoxControl chkShowCurrentItems;
        protected ICheckBoxControl chkShowArchivedItems;
        protected ITextControl txtMaxVisibleItems;
        protected ICheckBoxControl chkShowOnlyNewsForSelectedLocale;
        protected ListControl lstCategoryFilter;
        protected ICheckBoxControl chkAddFeedToPage;
        protected ITextControl txtFeedUrl;

        #endregion

        #region properties

        protected override string SkinUrl
        {
            get { return this.GetListSkinUrl(); }
            set { this.SetListSkinUrl(value); }
        }
 
        protected bool HasCategories
        {
            get
            {
                if (this.HasCoreModule)
                {
                    IList<string> categories = this.Controller.GetCategories();
                    return null != categories && categories.Count > 0;
                }
                return false;
            }
        }

        protected bool HasCoreModule
        {
            get
            {
                return this.Controller.HasCoreModule();
            }
        }

        #endregion

        #region page lifecycle

        protected override void OnInit(EventArgs e)
        {
            var tabs = Globals.GetPortalTabs(this.PortalSettings.DesktopTabs, false, true, false, false).Cast<TabInfo>().Where(tab => PortalSecurity.IsInRoles(tab.AuthorizedRoles));
            if (null != this.lstDetailTabId)
            {
                this.lstDetailTabId.DataSource = tabs;
                this.lstDetailTabId.DataTextField = "TabName";
                this.lstDetailTabId.DataValueField = "TabID";
                this.lstDetailTabId.DataBind();
                this.lstDetailTabId.Items.Insert(0, new ListItem(this.GetString("liUseDefault.Text", "<Use default>"), "-1"));
            }
            if (null != this.lstCategoryFilter)
            {
                if (this.HasCoreModule)
                {
                    this.lstCategoryFilter.DataSource = this.Controller.GetCategories();
                    this.lstCategoryFilter.DataBind();
                }
            }
        }

        #endregion

        #region methods

        protected string GetFeedUrl()
        {
            return this.ModuleConfiguration.GenerateFeedUrl();
        }

        /// <summary>
        /// Loads the module's settings into the given controls.
        /// </summary>
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        public override void LoadSettings()
        {
            base.LoadSettings();

            try
            {
                if (!this.Page.IsPostBack)
                {
                    // TODO: Fill control values from settings values here.
                    if (null != this.lstDetailTabId)
                    {
                        this.lstDetailTabId.SelectedValue = this.GetDetailTabId().ToString(CultureInfo.InvariantCulture);
                    }
                    if (null != this.chkShowCurrentItems)
                    {
                        this.chkShowCurrentItems.Checked = this.GetShowCurrentItems();
                    }
                    if (null != this.chkShowArchivedItems)
                    {
                        this.chkShowArchivedItems.Checked = this.GetShowArchivedItems();
                    }
                    if (null != this.txtMaxVisibleItems)
                    {
                        this.txtMaxVisibleItems.Text = this.GetMaxVisibleItems().ToString(CultureInfo.CurrentUICulture);
                    }
                    if (null != this.chkShowOnlyNewsForSelectedLocale)
                    {
                        this.chkShowOnlyNewsForSelectedLocale.Checked = this.GetShowOnlyNewsForSelectedLocale();
                    }
                    if (null != this.lstCategoryFilter)
                    {
                        ICollection<string> filters = this.GetCategoryFilter();
                        if (null != filters)
                        {
                            foreach (string filter in filters)
                            {
                                ListItem item = this.lstCategoryFilter.Items.FindByValue(filter);
                                if (null != item)
                                {
                                    item.Selected = true;
                                }
                            }
                        }
                    }
                    if (null != this.chkAddFeedToPage)
                    {
                        this.chkAddFeedToPage.Checked = this.GetAddFeedToPage();
                    }
                    if (null != this.txtFeedUrl)
                    {
                        this.txtFeedUrl.Text = this.GetFeedUrl();
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// <summary>
        /// Updates the module's settings from the given controls.
        /// </summary>
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        public override void UpdateSettings()
        {
            try
            {
                // TODO: Set settings from control values here.
                if (null != this.lstDetailTabId)
                {
                    int tabId;
                    if (int.TryParse(this.lstDetailTabId.SelectedValue, NumberStyles.None, CultureInfo.InvariantCulture, out tabId))
                    {
                        this.SetDetailTabId(tabId);
                    }
                }
                if (null != this.chkShowCurrentItems)
                {
                    this.SetShowCurrentItems(this.chkShowCurrentItems.Checked);
                }
                if (null != this.chkShowArchivedItems)
                {
                    this.SetShowArchivedItems(this.chkShowArchivedItems.Checked);
                }
                if (null != this.txtMaxVisibleItems)
                {
                    int maxVis;
                    if (int.TryParse(this.txtMaxVisibleItems.Text, NumberStyles.None, CultureInfo.CurrentUICulture, out maxVis))
                    {
                        this.SetMaxVisibleItems(maxVis);
                    }
                }
                if (null != this.chkShowOnlyNewsForSelectedLocale)
                {
                    this.SetShowOnlyNewsForSelectedLocale(this.chkShowOnlyNewsForSelectedLocale.Checked);
                }
                if (null != this.lstCategoryFilter)
                {
                    List<string> filters = new List<string>();
                    foreach (ListItem item in this.lstCategoryFilter.Items)
                    {
                        if (item.Selected)
                        {
                            filters.Add(item.Value);
                        }
                    }
                    this.SetCategoryFilter(filters);
                }
                if (null != this.chkAddFeedToPage)
                {
                    this.SetAddFeedToPage(this.chkAddFeedToPage.Checked);
                    if (this.chkAddFeedToPage.Checked)
                    {
                        this.ModuleConfiguration.DisplaySyndicate = true;
                        new ModuleController().UpdateModule(this.ModuleConfiguration);
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }

            base.UpdateSettings();
        }

        #endregion
    }
}